package com.zjj.lbw.algorithm.bit.base;

/**
 * @author zhanglei.zjj
 * @description 位运算运用，权限控制
 * @date 2023/6/23 11:23
 */
public class Permission {
    private static final int ALLOW_SELECT = 1 << 0;
    private static final int ALLOW_INSERT = 1 << 1;
    private static final int ALLOW_UPDATE = 1 << 2;
    private static final int ALLOW_DELETE = 1 << 3;

    static {
        System.out.println("ALLOW_SELECT: " + Integer.toBinaryString(ALLOW_SELECT));
        System.out.println("ALLOW_INSERT: " + Integer.toBinaryString(ALLOW_INSERT));
        System.out.println("ALLOW_UPDATE: " + Integer.toBinaryString(ALLOW_UPDATE));
        System.out.println("ALLOW_DELETE: " + Integer.toBinaryString(ALLOW_DELETE));
    }

    //当前的权限状态
    private int flag;

    public void setPermission(int permission) {
        flag = permission;
    }


    /*增加权限,可以一项或者多项*/
    public void addPermission(int permission) {
        flag = flag | permission;
    }

    /*删除权限,可以一项或者多项*/
    public void disablePermission(int permission) {
        flag = flag & ~permission;
    }

    /*是否拥有某些权限*/
    public boolean isAllow(int permission) {
        return (flag & permission) == permission;
    }

    /*是否不拥有某些权限*/
    public boolean isNotAllow(int permission) {
        return (flag & permission) == 0;
    }


    public static void main(String[] args) {
        int flag = 15;
        System.out.println("the binary 15 is : " + Integer.toBinaryString(15));

        Permission permission = new Permission();
        permission.setPermission(flag);
        permission.disablePermission(ALLOW_DELETE | ALLOW_INSERT);
        System.out.println("ALLOW_SELECT=" + permission.isAllow(ALLOW_SELECT));
        System.out.println("ALLOW_INSERT=" + permission.isAllow(ALLOW_INSERT));
        System.out.println("ALLOW_UPDATE=" + permission.isAllow(ALLOW_UPDATE));
        System.out.println("ALLOW_DELETE=" + permission.isAllow(ALLOW_DELETE));

        System.out.println("-10 >>> 1: " + (-10 >>> 1));
    }
}
